<template>
  <div id="panel">
    <template>
      <el-card class="queryForm">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          :label-position="'right'"
        >
          <el-form-item label="排污口名称：" prop="outfallname">
            <el-input
              v-model="queryParams.outfallname"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="行政区划：" prop="countycode" class="times">
            <el-select v-model="queryParams.countycode" placeholder="请选择">
              <el-option
                v-for="item in regionList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>

          <div class="searchBtnBox">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="padding: 10px"
              >查询</el-button
            >
            <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              清除
            </el-button>
            <el-button @click="handleAdd" type="success" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              新增
            </el-button>
          </div>
        </el-form>
      </el-card>
      <el-card class="pageContent">
        <el-table :data="tableList.rows" stripe :height="tableHeight">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="outfallname" label="排污口名称" />
          <el-table-column prop="outfallcode" label="排污口编码" />
          <el-table-column prop="dischargedwater" label="直接排入水体名称" />
          <el-table-column
            prop="finallydischargedwater"
            label="最终汇入水体名称"
          />
          <el-table-column prop="setunits" label="设置单位" />
          <el-table-column prop="agreesetunits" label="同意设置单位" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!-- <el-button type="text" @click="view(scope.row)">查看</el-button> -->
              <el-button type="text" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" @click="delRows(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagination-self"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :pager-count="5"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="slot, total, sizes, prev, pager, next, jumper"
          :total="tableList.total"
        >
          <el-button
            class="refresh-button"
            icon="el-icon-refresh"
            title="刷新"
            @click="getList"
          />
        </el-pagination>
      </el-card>
    </template>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="排口名称" prop="outfallname">
              <el-input
                v-model="form.outfallname"
                placeholder="请输入站点名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排污口编码" prop="outfallcode">
              <el-input
                v-model="form.outfallcode"
                placeholder="请输入站点代码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="行政区划名称" prop="countycode">
              <el-select
                v-model="form.countycode"
                placeholder="请选择行政区划"
                style="width: 100%"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属河流" prop="riverid">
              <el-select
                v-model="form.riverid"
                placeholder="请选择所属河流"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in options"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级水功能区名称" prop="onewatername">
              <el-input
                v-model="form.onewatername"
                placeholder="请输入站点代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级水功能区名称" prop="twowatername">
              <el-input
                v-model="form.twowatername"
                placeholder="请输入站点代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio v-model="form.state" label="1">启用</el-radio>
              <el-radio v-model="form.state" label="0">停用</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="直接排入水体名称" prop="dischargedwater">
              <el-input v-model="form.dischargedwater" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="最终汇入水体名称"
              prop="finallydischargedwater"
            >
              <el-input
                v-model="form.finallydischargedwater"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设置单位" prop="setunits">
              <el-input v-model="form.setunits" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="同意设置单位" prop="agreesetunits">
              <el-input v-model="form.agreesetunits" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRegionList } from "@/api/dataResources/monitorData/region.js";
import { getRiverList } from "@/api/dataResources/monitorData/river.js";
import {
  getPollutionList,
  getPollutionDetail,
  deletePollution,
  addPollution,
  editPollution,
} from "@/api/waterBusiness/interface.js";
export default {
  name: "HydrologicStation",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {},
  props: ["selTreeId"],
  computed: {},
  data() {
    // 自定义经度校验
    const validateLongitude = (rule, value, callback) => {
      if (!value) {
        // 非必填，为空时直接通过
        return callback();
      }
      // 经度范围：-180 至 180，保留6位小数
      const reg = /^-?((180(\.0{1,6})?)|((1[0-7]\d)|([1-9]?\d))(\.\d{1,6})?)$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的经度（-180至180，最多6位小数）"));
      }
    };

    // 自定义纬度校验
    const validateLatitude = (rule, value, callback) => {
      if (!value) {
        // 非必填，为空时直接通过
        return callback();
      }
      // 纬度范围：-90 至 90，保留6位小数
      const reg = /^-?((90(\.0{1,6})?)|(([1-8]?\d))(\.\d{1,6})?)$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入有效的纬度（-90至90，最多6位小数）"));
      }
    };
    return {
      tableHeight: window.innerHeight - 400,
      options: [
        { value: "河流1", label: "河流1" },
        { value: "河流2", label: "河流2" },
        { value: "河流3", label: "河流3" },
      ],
      regionList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outfallname: "",
        countycode: "",
        riverid: this.selTreeId,
      },
      tableList: {
        total: 0,
        rows: [],
      },
      dateRange: [],
      // 选中数组
      ids: [],
      tableData: [
        {
          date: "2016-05-02",
          name: "绿萃厂界",
          province: "2.52",
          lhq: "-",
          an: "-",
          voc: "0.250",
          fx: "东北偏东风",
          sd: "-",
          dqy: "-",
          ou: "-",
          swwd: "19.88",
          city: "普陀区",
          address: "上海市普陀区金沙江路 1518 弄",
          zip: 200333,
        },
      ],
      // 是否显示新增/修改弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        riverid: [
          { required: true, message: "河流名称不能为空", trigger: "change" },
        ],
        outfallname: [
          { required: true, message: "排口名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        outfallcode: [
          { required: true, message: "排污口编码不能为空", trigger: "blur" },
        ],
        latitude: [{ validator: validateLongitude, trigger: "blur" }],
        latitude: [{ validator: validateLatitude, trigger: "blur" }],
      },
      // 用于存储延迟请求的定时器
      requestTimer: null,
    };
  },
  watch: {
    selTreeId: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.riverid = newVal;
          // 有id时立即请求数据
          this.getList();
          // 清除可能存在的定时器
          if (this.requestTimer) {
            clearTimeout(this.requestTimer);
          }
        } else {
          // 没有id时延迟重试（这里设置1秒后重试）
          this.delayRequest();
        }
      },
      deep: true,
    },
  },
  created() {
    this.getsshl();
    this.getRegionList();
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    //页面初始化请求的数据
    pageInit() {
      this.getList();
    },
    // 延迟请求方法
    delayRequest() {
      // 清除之前的定时器，避免重复创建
      if (this.requestTimer) {
        clearTimeout(this.requestTimer);
      }

      // 1秒后再次检查id是否存在
      this.requestTimer = setTimeout(() => {
        if (this.itemId) {
          this.getList();
        } else {
          // 如果仍无id，继续延迟重试
          this.delayRequest();
        }
      }, 1000);
    },
    //获取行政区划下拉选项数据
    async getRegionList() {
      let res = await getRegionList();
      if (res.code == 200) {
        this.regionList = res.rows;
      }
    },
    //获取所属河流下拉选项数据
    getsshl() {
      getRiverList().then((response) => {
        console.log(">>>河流", response);

        this.options = response.rows.map((item) => ({
          value: item.id,
          label: item.rivername,
        }));
      });
    },
    //表格checkbox选择数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    // 行间编辑
    edit(row) {
      this.open = true;
      // this.formType = "edit";
      this.title = "修改";
      this.form = { ...row };
      this.form.lifeStatus = row.lifeStatus === "1";
    },
    // 删除行
    delRows(row) {
      const userIds = row.id;
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return deletePollution(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNum = val;
      this.getList();
    },
    //搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置、清除表单
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
    },
    // 弹出层取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        outfallname: "",
        outfallcode: "",
        countycode: "",
        onewatername: "",
        twowatername: "",
        state: "",
        longitude: "",
        latitude: "",
        dischargedwater: "",
        finallydischargedwater: "",
        setunits: "",
        agreesetunits: "",
        address: "",
        riverid: "",
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            editPollution(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPollution(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //导出
    handleExport() {},
    // 获取表格数据
    getList() {
      getPollutionList(this.queryParams)
        .then((response) => {
          console.log(">>>一河一档_获取排污口列表", response);
          this.tableList.total = response.total;
          this.tableList.rows = response.rows;
        })
        .catch((error) => {
          this.$message.error("获取数据失败: " + error.message);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  // 控制分页的样式----二次开发
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  // 控制分页刷新按钮样式
  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    // .el-card__body {
    //   padding-left: 0 !important;
    // }
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
      // & > div {
      //   width: 100% !important;
      // }
    }

    .searchBtnBox {
      display: inline-block;
      margin: 10px 0 10px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}
</style>
